<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading">
      <el-form-item label="年份" prop="years">
        <el-date-picker v-model="formData.years" type="year" format="YYYY" value-format="YYYY" placeholder="选择年份" />
      </el-form-item>
      <el-form-item label="月份" prop="month">
        <el-date-picker v-model="formData.month" type="month" format="MM" value-format="MM" placeholder="选择月份" />
      </el-form-item>
      <el-form-item label="姓名" prop="userName">
        <UserSelect v-model="formData.userId" @node-change="handleUserChange" />
      </el-form-item>
      <el-form-item label="基本工资" prop="baseSalary">
        <el-input v-model="formData.baseSalary" placeholder="请输入基本工资" />
      </el-form-item>
      <el-form-item label="岗位工资" prop="positionSalary">
        <el-input v-model="formData.positionSalary" placeholder="请输入岗位工资" />
      </el-form-item>
      <el-form-item label="工资小计" prop="salarySubtotal">
        <el-input v-model="formData.salarySubtotal" placeholder="请输入工资小计" />
      </el-form-item>
      <el-form-item label="考勤天数" prop="attendanceDays">
        <el-input v-model="formData.attendanceDays" placeholder="请输入考勤天数" />
      </el-form-item>
      <el-form-item label="公休/调休" prop="publicHolidayCompensatoryLeave">
        <el-input v-model="formData.publicHolidayCompensatoryLeave" placeholder="请输入公休/调休" />
      </el-form-item>
      <el-form-item label="病假" prop="sickLeave">
        <el-input v-model="formData.sickLeave" placeholder="请输入病假" />
      </el-form-item>
      <el-form-item label="事假" prop="personalLeave">
        <el-input v-model="formData.personalLeave" placeholder="请输入事假" />
      </el-form-item>
      <el-form-item label="其他" prop="otherLeave">
        <el-input v-model="formData.otherLeave" placeholder="请输入其他" />
      </el-form-item>
      <el-form-item label="产检假" prop="maternityCheckupLeave">
        <el-input v-model="formData.maternityCheckupLeave" placeholder="请输入产检假" />
      </el-form-item>
      <el-form-item label="扣除金额" prop="deductionAmount">
        <el-input v-model="formData.deductionAmount" placeholder="请输入扣除金额" />
      </el-form-item>
      <el-form-item label="出勤天数" prop="actualAttendanceDays">
        <el-input v-model="formData.actualAttendanceDays" placeholder="请输入出勤天数" />
      </el-form-item>
      <el-form-item label="平日加班" prop="weekdayOvertime">
        <el-input v-model="formData.weekdayOvertime" placeholder="请输入平日加班" />
      </el-form-item>
      <el-form-item label="双休日加班" prop="weekendOvertime">
        <el-input v-model="formData.weekendOvertime" placeholder="请输入双休日加班" />
      </el-form-item>
      <el-form-item label="节假日加班" prop="holidayOvertime">
        <el-input v-model="formData.holidayOvertime" placeholder="请输入节假日加班" />
      </el-form-item>
      <el-form-item label="加班费" prop="overtimePay">
        <el-input v-model="formData.overtimePay" placeholder="请输入加班费" />
      </el-form-item>
      <el-form-item label="迟到早退" prop="lateEarlyDeduction">
        <el-input v-model="formData.lateEarlyDeduction" placeholder="请输入迟到早退" />
      </el-form-item>
      <el-form-item label="错漏" prop="errorOmission">
        <el-input v-model="formData.errorOmission" placeholder="请输入错漏" />
      </el-form-item>
      <el-form-item label="其他扣款" prop="otherDeductions">
        <el-input v-model="formData.otherDeductions" placeholder="请输入其他扣款" />
      </el-form-item>
      <el-form-item label="调整工资" prop="adjustedSalary">
        <el-input v-model="formData.adjustedSalary" placeholder="请输入调整工资" />
      </el-form-item>
      <el-form-item label="绩效工资" prop="performanceSalary">
        <el-input v-model="formData.performanceSalary" placeholder="请输入绩效工资" />
      </el-form-item>
      <el-form-item label="出差津贴" prop="businessTripAllowance">
        <el-input v-model="formData.businessTripAllowance" placeholder="请输入出差津贴" />
      </el-form-item>
      <el-form-item label="高温补贴" prop="highTemperatureAllowance">
        <el-input v-model="formData.highTemperatureAllowance" placeholder="请输入高温补贴" />
      </el-form-item>
      <el-form-item label="调整社保(扣)" prop="adjustedSocialSecurityDeduction">
        <el-input v-model="formData.adjustedSocialSecurityDeduction" placeholder="请输入调整社保(扣)" />
      </el-form-item>
      <el-form-item label="外派补贴" prop="expatriateAllowance">
        <el-input v-model="formData.expatriateAllowance" placeholder="请输入外派补贴" />
      </el-form-item>
      <el-form-item label="其他" prop="otherAllowance">
        <el-input v-model="formData.otherAllowance" placeholder="请输入其他" />
      </el-form-item>
      <el-form-item label="核薪小计" prop="payrollReviewSubtotal">
        <el-input v-model="formData.payrollReviewSubtotal" placeholder="请输入核薪小计" />
      </el-form-item>
      <el-form-item label="个人缴纳基本养老保险费" prop="individualBasicEndowmentInsurance" label-width="180px">
        <el-input v-model="formData.individualBasicEndowmentInsurance" placeholder="请输入个人缴纳基本养老保险费" />
      </el-form-item>
      <el-form-item label="个人缴纳基本医疗保险费" prop="individualBasicMedicalInsurance" label-width="180px">
        <el-input v-model="formData.individualBasicMedicalInsurance" placeholder="请输入个人缴纳基本医疗保险费" />
      </el-form-item>
      <el-form-item label="个人缴纳失业保险费" prop="individualUnemploymentInsurance" label-width="180px">
        <el-input v-model="formData.individualUnemploymentInsurance" placeholder="请输入个人缴纳失业保险费" />
      </el-form-item>
      <el-form-item label="个人社保缴纳小计" prop="individualSocialSecuritySubtotal" label-width="150px">
        <el-input v-model="formData.individualSocialSecuritySubtotal" placeholder="请输入个人社保缴纳小计" />
      </el-form-item>
      <el-form-item label="公司社保缴纳" prop="companySocialSecurityContribution">
        <el-input v-model="formData.companySocialSecurityContribution" placeholder="请输入公司社保缴纳" />
      </el-form-item>
      <el-form-item label="个人公积金缴纳" prop="individualHousingFund">
        <el-input v-model="formData.individualHousingFund" placeholder="请输入个人公积金缴纳" />
      </el-form-item>
      <el-form-item label="公司公积金缴纳" prop="companyHousingFund">
        <el-input v-model="formData.companyHousingFund" placeholder="请输入公司公积金缴纳" />
      </el-form-item>
      <el-form-item label="应付工资" prop="payableSalary">
        <el-input v-model="formData.payableSalary" placeholder="请输入应付工资" />
      </el-form-item>
      <el-form-item label="个调税" prop="individualIncomeTax">
        <el-input v-model="formData.individualIncomeTax" placeholder="请输入个调税" />
      </el-form-item>
      <el-form-item label="应发工资" prop="grossSalaryPayable">
        <el-input v-model="formData.grossSalaryPayable" placeholder="请输入应发工资" />
      </el-form-item>
      <el-form-item label="餐补" prop="mealAllowance">
        <el-input v-model="formData.mealAllowance" placeholder="请输入餐补" />
      </el-form-item>
      <el-form-item label="交补" prop="transportationAllowance">
        <el-input v-model="formData.transportationAllowance" placeholder="请输入交补" />
      </el-form-item>
      <el-form-item label="其他" prop="otherFinal">
        <el-input v-model="formData.otherFinal" placeholder="请输入其他" />
      </el-form-item>
      <el-form-item label="合计" prop="totalAmount">
        <el-input v-model="formData.totalAmount" placeholder="请输入合计" />
      </el-form-item>
      <el-form-item label="发布状态" prop="publishStatus">
        <el-select v-model="formData.publishStatus" placeholder="请选择发布状态">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.OA_PUBLISH_STATUS)" :key="dict.value"
            :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EmployeeSalaryApi, EmployeeSalaryVO } from '@/api/oa/employeesalary'
import UserSelect from '@/views/system/user/UserSelect.vue'

/** 员工工资 表单 */
defineOptions({ name: 'EmployeeSalaryForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  years: undefined as string | undefined,
  month: undefined as string | undefined,
  userId: undefined,
  userName: undefined,
  company: undefined,
  baseSalary: undefined,
  positionSalary: undefined,
  salarySubtotal: undefined,
  attendanceDays: undefined,
  publicHolidayCompensatoryLeave: undefined,
  sickLeave: undefined,
  personalLeave: undefined,
  otherLeave: undefined,
  maternityCheckupLeave: undefined,
  deductionAmount: undefined,
  actualAttendanceDays: undefined,
  weekdayOvertime: undefined,
  weekendOvertime: undefined,
  holidayOvertime: undefined,
  overtimePay: undefined,
  lateEarlyDeduction: undefined,
  errorOmission: undefined,
  otherDeductions: undefined,
  adjustedSalary: undefined,
  performanceSalary: undefined,
  businessTripAllowance: undefined,
  highTemperatureAllowance: undefined,
  adjustedSocialSecurityDeduction: undefined,
  expatriateAllowance: undefined,
  otherAllowance: undefined,
  payrollReviewSubtotal: undefined,
  individualBasicEndowmentInsurance: undefined,
  individualBasicMedicalInsurance: undefined,
  individualUnemploymentInsurance: undefined,
  individualSocialSecuritySubtotal: undefined,
  companySocialSecurityContribution: undefined,
  individualHousingFund: undefined,
  companyHousingFund: undefined,
  payableSalary: undefined,
  individualIncomeTax: undefined,
  grossSalaryPayable: undefined,
  mealAllowance: undefined,
  transportationAllowance: undefined,
  otherFinal: undefined,
  totalAmount: undefined,
  publishStatus: undefined,
})
const formRules = reactive({
  years: [{ required: true, message: '年份不能为空', trigger: 'blur' }],
  month: [{ required: true, message: '月份不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '员工ID不能为空', trigger: 'blur' }],
  userName: [{ required: true, message: '员工姓名不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const data = await EmployeeSalaryApi.getEmployeeSalary(id)
      formData.value = data
      // 修复TypeScript类型错误：确保年月字段为字符串格式用于日期选择器
      if (data.years !== undefined && data.years !== null) {
        formData.value.years = String(data.years)
      }
      if (data.month !== undefined && data.month !== null) {
        formData.value.month = data.month < 10 ? '0' + String(data.month) : String(data.month)
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = { ...formData.value } as any
    // 确保年月字段以数字形式提交
    if (data.years) {
      data.years = parseInt(data.years)
    }
    if (data.month) {
      data.month = parseInt(data.month)
    }
    
    if (formType.value === 'create') {
      await EmployeeSalaryApi.createEmployeeSalary(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeSalaryApi.updateEmployeeSalary(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    years: undefined,
    month: undefined,
    userId: undefined,
    userName: undefined,
    company: undefined,
    baseSalary: undefined,
    positionSalary: undefined,
    salarySubtotal: undefined,
    attendanceDays: undefined,
    publicHolidayCompensatoryLeave: undefined,
    sickLeave: undefined,
    personalLeave: undefined,
    otherLeave: undefined,
    maternityCheckupLeave: undefined,
    deductionAmount: undefined,
    actualAttendanceDays: undefined,
    weekdayOvertime: undefined,
    weekendOvertime: undefined,
    holidayOvertime: undefined,
    overtimePay: undefined,
    lateEarlyDeduction: undefined,
    errorOmission: undefined,
    otherDeductions: undefined,
    adjustedSalary: undefined,
    performanceSalary: undefined,
    businessTripAllowance: undefined,
    highTemperatureAllowance: undefined,
    adjustedSocialSecurityDeduction: undefined,
    expatriateAllowance: undefined,
    otherAllowance: undefined,
    payrollReviewSubtotal: undefined,
    individualBasicEndowmentInsurance: undefined,
    individualBasicMedicalInsurance: undefined,
    individualUnemploymentInsurance: undefined,
    individualSocialSecuritySubtotal: undefined,
    companySocialSecurityContribution: undefined,
    individualHousingFund: undefined,
    companyHousingFund: undefined,
    payableSalary: undefined,
    individualIncomeTax: undefined,
    grossSalaryPayable: undefined,
    mealAllowance: undefined,
    transportationAllowance: undefined,
    otherFinal: undefined,
    totalAmount: undefined,
    publishStatus: undefined,
  }
  formRef.value?.resetFields()
}

const handleUserChange = (row: any) => {
  formData.value.userId = row.id
  formData.value.userName = row.nickname
}
</script>